package com.aim.common.service;

import com.aim.common.entity.ZTreeNode;
import com.aim.common.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @AUTO 地区设置服务实现类
 * @Author AIM
 * @DATE 2019/07/09
 */
@Service("area")
public class FitAreaService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据父级CODE查询
     */
    public List<Map<String, Object>> getArea(String pcode) {
        if (OftenUtil.isEmpty(pcode)) pcode = "0";
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT `CODE`,`NAME`,`SHORT_NAME`,`LNG`,`LAT`,`SORT` FROM (");
        sb.append(" SELECT `PARENT_CODE`,`CODE`,`NAME`,`SHORT_NAME`,`LNG`,`LAT`,`SORT` FROM `fit_province` ");
        sb.append(" UNION ALL SELECT `PARENT_CODE`,`CODE`,`NAME`,`SHORT_NAME`,`LNG`,`LAT`,`SORT` FROM `fit_city` ");
        sb.append(" UNION ALL SELECT `PARENT_CODE`,`CODE`,`NAME`,`SHORT_NAME`,`LNG`,`LAT`,`SORT` FROM `fit_area` ");
        sb.append(" UNION ALL SELECT `PARENT_CODE`,`CODE`,`NAME`,`SHORT_NAME`,`LNG`,`LAT`,`SORT` FROM `fit_street` ");
        sb.append(" )z WHERE z.`PARENT_CODE`=?");
        List<Map<String, Object>> maps = JdbcTemplateUtil.queryForListMap(jdbcTemplate, sb.toString(), pcode);
        return maps;
    }

    /**
     * 地区树结构
     */
    public List<ZTreeNode> areaZtree() {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT `CODE` AS id,`PARENT_CODE` AS parentId,`NAME`,");
        sb.append("(CASE WHEN (`PARENT_CODE` IS NULL) THEN 'true' ELSE 'false' END) AS `open` ");
        sb.append("FROM ( SELECT `PARENT_CODE`,`CODE`,`NAME` FROM `fit_province` ");
        sb.append(" UNION ALL SELECT `PARENT_CODE`,`CODE`,`NAME` FROM `fit_area` ");
        sb.append(" UNION ALL SELECT `PARENT_CODE`,`CODE`,`NAME` FROM `fit_city` )z");

        return JdbcTemplateUtil.queryForListBean(jdbcTemplate, sb.toString(), ZTreeNode.class);
    }
}